package com.gs.synedocket.service;

import static org.greenrobot.eventbus.ThreadMode.BACKGROUND;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.Nullable;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.model.LatLng;
import com.gs.synedocket.R;
import com.gs.synedocket.constant.AllConstants;
import com.gs.synedocket.constant.EventCode;
import com.gs.synedocket.db.bean.Event;
import com.gs.synedocket.db.dao.LogUtil;
import com.gs.synedocket.util.AppUtil;
import com.gs.synedocket.util.CoordinateUtil;
import com.gs.synedocket.util.LanguageUtils;
import com.gs.synedocket.util.NetworkUtil;
import com.gs.synedocket.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.IOException;
import java.util.Locale;

import taobe.tec.jcc.JChineseConvertor;

public class GpsService extends Service {

    private AMapLocationClientOption mLocationOption = null;
    private AMapLocationClient mLocationClient = null;
    private AMapLocationListener mLocationListener = null;
    private AMapLocationClientOption.AMapLocationMode mMode;
    private static String gps = "";
    private static String gpsLoc = "";

    public static String getGps() {
        return gps;
    }

    public static String getGpsLoc() {
        return gpsLoc;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        initLocation();
        startLocation();
        return START_STICKY;
    }

    private void initLocation() {
        if (mLocationListener == null) {
            mLocationListener = aMapLocation -> {
                if (aMapLocation == null) {
                    String msg = "location is null";
                    Log.d(AllConstants.TAG, msg);
                    LogUtil.getInstance().insertOrReplaceData(msg);
                    ToastUtil.showToast(R.string.gps_null);
                    return;
                }
                if (aMapLocation.getErrorCode() != 0) {
                    String msg = "location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo().substring(0,aMapLocation.getErrorInfo().indexOf("，"));
                    LogUtil.getInstance().insertOrReplaceData(msg);
                    Log.e(AllConstants.TAG, msg);
                    Log.e(AllConstants.TAG, aMapLocation.getLocationDetail());
                    ToastUtil.showToast(R.string.gps_null);
                    return;
                }
                // 定位成功
                handleLocation(aMapLocation);
            };
        }
        if (mLocationOption == null) {
            mLocationOption = getOption();
        }
        if (mLocationClient == null) {
            mLocationClient = new AMapLocationClient(AppUtil.getInstance().getContext());
            mLocationClient.setLocationListener(mLocationListener);
        }
        mMode = NetworkUtil.getInstance().getNetworkSignal() ? AMapLocationClientOption.AMapLocationMode.Hight_Accuracy : AMapLocationClientOption.AMapLocationMode.Device_Sensors;
    }

    private void handleLocation(AMapLocation aMapLocation) {
        LatLng point = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
        point = CoordinateUtil.GCJToWGS(point);
        gps = String.format(LanguageUtils.getInstance().getCurrentLanguage(), "%.6f/%.6f", point.latitude, point.longitude);
        gpsLoc = aMapLocation.getAddress();
        if (!TextUtils.isEmpty(gpsLoc)) {
            if (gpsLoc.contains("香港特别行政区")) {
                gpsLoc = gpsLoc.replace("香港特别行政区", "");
            }
            if (LanguageUtils.getInstance().getCurrentLanguage() == Locale.TAIWAN) {
                try {
                    gpsLoc = JChineseConvertor.getInstance().s2t(gpsLoc);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private AMapLocationClientOption getOption() {
        AMapLocationClientOption option = new AMapLocationClientOption();
        option.setNeedAddress(true);
        option.setOnceLocation(false);
        option.setOnceLocationLatest(false);
        option.setInterval(5000);
        option.setHttpTimeOut(20000);
        option.setWifiScan(true);
        option.setLocationCacheEnable(true);
        return option;
    }

    private void startLocation() {
        mLocationOption.setLocationMode(mMode);
        mLocationClient.setLocationOption(mLocationOption);
        mLocationClient.startLocation();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.disableBackgroundLocation(true);
            mLocationClient.stopLocation();
            mLocationClient.unRegisterLocationListener(mLocationListener);
            mLocationClient.onDestroy();
            mLocationClient = null;
        }
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = BACKGROUND)
    public void onEvent(Event event) {
        if (event.getWhat() == EventCode.EVENT_NETWORK_CHANGE) {
            AMapLocationClientOption.AMapLocationMode mode = NetworkUtil.getInstance().getNetworkSignal() ? AMapLocationClientOption.AMapLocationMode.Hight_Accuracy : AMapLocationClientOption.AMapLocationMode.Device_Sensors;
            if (mode != mMode) {
                mMode = mode;
                mLocationClient.stopLocation();
                startLocation();
            }
        }
    }
}
